package josema.org.influenciasolar;

import java.text.SimpleDateFormat;
import java.util.Date;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class DateActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_date);

        // debug
    	EditText editDate = (EditText) findViewById( R.id.editDate );
    	editDate.setText("16/08/1975");
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.activity_date, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
      switch (item.getItemId()) {
      case R.id.itemBackDate:
      	Intent intent = new Intent(this, MainActivity.class);
      	startActivity(intent);
        break;
          
      default:
        break;
      }

      return true;
    }
    
    //
    // BUTTON CALC. 
    // This button check DATE input. Then go to 
    // Circles Activity
    //
    public void onClickCalc (View view){
    
    	// Define EditDate with date input
    	EditText editDate = (EditText) findViewById( R.id.editDate );
    	
    	String value = editDate.getText().toString() ;
    	
    	// First, check the valid date
    	if ( CheckValidDate (value) )
    	{    		
    		// Show RESULT Activity
    		Intent intent = new Intent(this, ResultActivity.class);
    		intent.putExtra("inputDate", value);
        	startActivity(intent);
    		
    	}
    	else
    	{
    		// DATE is wrong. Show a message 
    		Toast.makeText(this, R.string.msgErrorDate, Toast.LENGTH_SHORT)
            .show();    		
    	}
    
    }

    
    //
    // Private method that check correct date.
    private boolean CheckValidDate (String value){

    	// Define format expected
    	SimpleDateFormat  format = new SimpleDateFormat("dd/MM/yyyy");  
    	
    	try {
    		// try parse 
        	Date resultado = new Date();
    		resultado = format.parse(value);
    		
    		// Parse Ok. Format Ok.
    		return true;
    		
    	} catch (Exception e) {
    		// Error in parse. Format not correct
			return false;
		}
    	
    }
    
}
